package com.bkhc.common.listener;

import com.bkhc.common.annotation.Password;
import com.bkhc.common.annotation.Uid;
import com.bkhc.common.util.IdWorker;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.persistence.PostPersist;
import javax.persistence.PrePersist;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Random;

@Slf4j
@Component
public class DataEntityListener {
    @Autowired
    private IdWorker idWorker;

    @PrePersist
    public void prePersist(Object object)
            throws IllegalArgumentException, IllegalAccessException {
        Class<?> o = object.getClass();
        Field[] fields = o.getDeclaredFields();
        for(Field f:fields){
            f.setAccessible(true);
            Annotation[] anno = f.getAnnotations();
            if(anno!=null&&anno.length>0){
                for(Annotation annotation:anno){
                    if(annotation.annotationType().equals(Uid.class)){
                        f.set(object,idWorker.nextId()+"");
                    }
//                    if(annotation.annotationType().equals(GenerateEmployeeNo.class)){
//                        try {
//                            Method method = o.getMethod("init", new Class[]{int.class});
//                            method.invoke(o,generateEmployeeNo());
//                        } catch (NoSuchMethodException e) {
//                            e.printStackTrace();
//                        } catch (InvocationTargetException e) {
//                            e.printStackTrace();
//                        }
//                    }
                    if(annotation.annotationType().equals(Password.class)){
                        f.set(object,generatePassword(f.get(object).toString()));
                    }
                }
            }
        }
    }


    public int generateEmployeeNo(){
//        int maxEmpNo= repository.findMaxEmpNo();
//        return maxEmpNo+1;
        return 1;
    }



    public String generatePassword(String password){
        return  new BCryptPasswordEncoder().encode(password);
    }



}
